package com.itgaohe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itgaohe.dao.entity.SeckillVoucher;
import com.itgaohe.dao.entity.Voucher;
import com.itgaohe.dao.mapper.SeckillVoucherMapper;
import com.itgaohe.dao.mapper.VoucherMapper;
import com.itgaohe.dto.VoucherDTO;
import com.itgaohe.dto.resp.SearchVoucherInfoDTO;
import com.itgaohe.service.VoucherService;
import com.itgaohe.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements VoucherService {
    private final VoucherMapper voucherMapper;
    private final SeckillVoucherMapper seckillVoucherMapper;

    /**
     * 根据用户id查询优惠券
     * @param shopId 商户id
     * @return
     */
    @Override
    public Result getVoucherByShopId(Long shopId) {
        // 2. 查询基础优惠券信息
        LambdaQueryWrapper<Voucher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Voucher::getShopId, shopId);
        List<Voucher> voucherList = voucherMapper.selectList(wrapper);

        if (CollectionUtils.isEmpty(voucherList)) {
            return Result.fail("该商户暂无优惠券");
        }

        // 3. 提取秒杀券ID（优化查询）
        List<Long> seckillVoucherIds = voucherList.stream()
                .filter(v -> v.getType() == 1)
                .map(Voucher::getId)
                .collect(Collectors.toList());

        // 4. 批量查询秒杀信息（避免N+1问题）
        Map<Long, SeckillVoucher> seckillMap = new HashMap<>();
        if (!seckillVoucherIds.isEmpty()) {
            List<SeckillVoucher> seckillVouchers = seckillVoucherMapper.selectList(
                    new LambdaQueryWrapper<SeckillVoucher>()
                            .in(SeckillVoucher::getVoucherId, seckillVoucherIds)
            );
            seckillMap = seckillVouchers.stream()
                    .collect(Collectors.toMap(SeckillVoucher::getVoucherId, Function.identity()));
        }

        // 5. 创建统一DTO列表
        List<VoucherDTO> resultList = new ArrayList<>();
        for (Voucher voucher : voucherList) {
            VoucherDTO dto = new VoucherDTO();
            // 复制基础字段
            BeanUtils.copyProperties(voucher, dto);


            // 添加秒杀信息（如果是秒杀券）
            if (voucher.getType() == 1) {
                SeckillVoucher seckill = seckillMap.get(voucher.getId());
                if (seckill != null) {
                    dto.setStock(seckill.getStock());
                    dto.setBeginTime(seckill.getBeginTime());
                    dto.setEndTime(seckill.getEndTime());
                }
            }
            resultList.add(dto);
        }

        long count = resultList.size();
        log.info("查询到优惠券数量：{}", voucherList.size());
        log.info("最终DTO数量：{}", resultList.size());
        resultList.forEach(dto -> log.info("DTO内容：{}", dto));
        // 6. 返回成功结果
        return Result.ok(resultList, count);

    }
}
